<template>
<el-row>
    <el-row> 
        <!--新增界面 Archive 档案信息表--> 
        <el-form :model="editForm"  label-width="120px" :rules="editFormRules" ref="editForm"> 
        
        
            <el-form-item label="标题" prop="archiveTitle">
                <el-input  name="name" v-model="editForm.archiveTitle" required :maxlength="100"  @change="editSomeFields(editForm,'archiveTitle',$event)">标题 </el-input>
                <mdp-select-tag show-style="tag" :multiple="true" split="," v-model="editForm.tagIds" @change2="editSomeFields(editForm,'tagIds',$event)"></mdp-select-tag>
            </el-form-item>
            <el-form-item label="摘要" prop="archiveAbstract">
                <el-input name="name" v-model="editForm.archiveAbstract" required :maxlength="100"  @change="editSomeFields(editForm,'archiveAbstract',$event)">摘要 </el-input>
                   
            </el-form-item>
            <el-form-item label="作者"> 
                <el-row :gutter="20"> 
                    <el-col :span="6">
                        <el-input    v-model="editForm.authorName" placeholder="请输入作者名称" @change="editSomeFields(editForm,'authorName',$event)"></el-input>
                    </el-col>
                    <el-col :span="6">
                        <mdp-select v-model="editForm.archiveType" :disabled="!!archiveType" item-code="categoryType"  placeholder="请选择主题"  @change="editSomeFields(editForm,'archiveType',$event)"/>
                                    
                    </el-col>  
                    <el-col :span="6">  
                        <mdp-select item-code="archiveStatus" v-model="editForm.status" :disabled="!!archiveType"  placeholder="状态"  @change="editSomeFields(editForm,'archiveStatus',$event)"/> 
                    </el-col>  
                </el-row> 
            </el-form-item> 
        <el-tabs v-model="activeTabPaneName">
        <el-tab-pane  label="正文" name="1"> 
            <vue-ueditor v-if="visible&&activeTabPaneName=='1'" :key="editForm.id?editForm.id:'xxxxx'" class="rich-context" v-model="editForm.archiveContext"></vue-ueditor>  
            <el-row v-if="currOpType=='edit' && editForm.archiveContext!==dataBak.archiveContext" class="padding"> 
                <el-button type="primary" @click="editSomeFields(editForm,'archiveContext',editForm.archiveContext)">保存正文</el-button>
            </el-row>
        </el-tab-pane> 
        <el-tab-pane label="推广" name="2"> 
 
                <el-form-item label="排序号" prop="seqNo"> 
                <el-input type="number" v-model="editForm.seqNo"  placeholder="排序"  @change="editSomeFields(editForm,'seqNo',$event)"/>    
            </el-form-item> 
                <el-form-item label="置顶推荐" prop="isMain,isHot"> 
                <el-checkbox v-model="editForm.isMain" true-label="1" false-label="0"  @change="editSomeFields(editForm,'isMain',$event)">   置顶 </el-checkbox>   
                <el-checkbox  v-model="editForm.isHot" true-label="1" false-label="0"  @change="editSomeFields(editForm,'isHot',$event)">   推荐 </el-checkbox>   
                <el-checkbox v-model="editForm.canComment" align="center" true-label="1" false-label="0" @change="editSomeFields(editForm,'canComment',$event)">打开评论</el-checkbox> 
            </el-form-item> 
        </el-tab-pane> 
        <el-tab-pane label="附件"  name="3" v-if="currOpType=='edit'"> 
            <mdp-select-att crely-type="archiveType" :crely-id="editForm.archiveType"  crely-stype="archiveId" :crely-sid="editForm.id"></mdp-select-att>   
        </el-tab-pane> 
            <el-tab-pane label="轮播图片"  name="4">
                 <mdp-image :value="imageUrls.map(k=>k.linkUrl)"  :multiple="true" @change2="onImageSelect" placeholder="选择图片"></mdp-image>
                 <el-row class="padding">
                    <el-button v-if="editForm.imageUrls && editForm.imageUrls.length>0" @click="onImageSelect([])">清除图片</el-button>

                    <el-button v-if="currOpType=='edit' && editForm.imageUrls!==dataBak.imageUrls" type="primary" @click="saveLink('imageUrls')">保存轮播图</el-button>
                 </el-row>
            </el-tab-pane>
            <el-tab-pane label="关联文章"  name="5"> 
                <mdp-select-table :value="linkArchives.map(k=>k.id)" :props="{id:'id',name:'archiveTitle'}" :load-fun="apis.list" @change2="onArchiveSelect" :multiple="true"></mdp-select-table>
                
                <el-row v-if="currOpType=='edit' && editForm.linkArchives!==dataBak.linkArchives" class="padding"> 
                    <el-button type="primary" @click="saveLink('linkArchives')">保存关联文章</el-button>
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="关联广告"  name="6">
                <mdp-select-table :value="linkAds.map(k=>k.id)" :props="{id:'id',name:'name'}" :load-fun="apis.listAds" @change2="onAdSelect" :multiple="true"></mdp-select-table>

                
                <el-row v-if="currOpType=='edit' && editForm.linkAds!==dataBak.linkAds" class="padding"> 
                    <el-button type="primary" @click="saveLink('linkAds')">保存广告</el-button>
                </el-row>
            </el-tab-pane>
            <!--
            <el-tab-pane label="关联用户">
                <multiple-shear-upload
                    limit="15"
                    :img-width="300"
                    :img-height="300"
                    :url-name="'imgUrl'"
                    :value-name="'linkUrl'"
                    :des-name="'imgDesc'"
                    v-model="linkUsers"
                    :deptid="editForm.deptid"
                    show-add="true"
                    :branch-id="editForm.branchId"
                    :remark="editForm.name" 
                ></multiple-shear-upload>
            </el-tab-pane>
            -->
            <el-tab-pane label="其它信息"  name="7">
                    <mdp-ext-infos v-model="editForm.extInfos"></mdp-ext-infos>  
                <el-row v-if="currOpType=='edit' && editForm.extInfos!==dataBak.extInfos" class="padding"> 
                    <el-button type="primary" @click="editSomeFields(editForm,'extInfos',editForm.extInfos)">保存扩展信息</el-button>
                </el-row>
            </el-tab-pane>
            
        </el-tabs>
        
        </el-form> 
    </el-row>
    <slot name="footer" :page="this">
        <el-row v-if="showBtn!==false" style="float:right;" class="footer">
            <el-button @click.native="close">关闭</el-button>
            <el-button v-if="currOpType=='add'" type="primary" @click="saveSubmit('0')">存为草稿</el-button>
            <el-button v-if="currOpType=='add'" @click="saveSubmit('1')">保存并发布</el-button>
         </el-row>
    </slot>
 
</el-row>
</template>

<script>
import * as ArchiveApi from '@/api/mdp/arc/archive/archive';
import {listAdvert} from '@/api/mdp/arc/ad/advert';

import { mapGetters } from 'vuex'
import { MdpFormMixin } from '@/components/mdp-ui/mixin/MdpFormMixin.js';
 import MDinput from '@/components/MDinput'  
import VueUeditor from '@/components/Tinymce/index';   
export default {
    name:'archiveForm',
    mixins:[MdpFormMixin],
    components: { 
			 VueUeditor
    },
    computed: {
    },
    props:{
        archiveType:String,
        categoryId:String,
    },
    watch: {
    },
    data() {
        return {
            menuDefId:'',//menu_def.id 菜单表菜单编号，用于按钮权限判断
            pkNames:["id"],//表格主键的java属性名称，驼峰命名，默认为id,支持多主键
            currOpType:'add',//表单 add、edit，所有按钮可动、detail-只看不能操作
            editFormRules: {
                id:[
                //{ required: true, message: '此项必填', trigger: 'change' },
                //{ min: 1,max: 200, message: '长度在1到200之间', trigger: 'change'}
                ]
            },
            editForm: {
                id:'',tagNames:'',deptid:'',userid:'',isShare:'',url:'',archiveAbstract:'',archiveContext:'',archiveTitle:'',archivingUserid:'',isFromArchiving:'',archivingDate:'',createDate:'',authorUserid:'',authorName:'',canDel:'',canEdit:'',canRead:'',bizKey:'',encryptType:'',canComment:'',status:'',isStorageDir:'',branchId:'',titleImgUrl:'',type:'',duration:'',tagIds:'',archiveType:'',imageUrls:'',linkArchives:'',readNums:'',commentNums:'',linkAds:'',linkUsers:'',extInfos:'',praiseSum:'',isHot:'',isMain:'',opDate:'',seqNo:'',pbizKey:'',ctime:'',ip:'',cityId:'',cityName:'',upNums:'',collectNums:'',relyTypes:'',relyIds:'',relySubTypes:'',relySubIds:''
            },
            editFormInit: {
                id:'',tagNames:'',deptid:'',userid:'',isShare:'',url:'',archiveAbstract:'',archiveContext:'',archiveTitle:'',archivingUserid:'',isFromArchiving:'',archivingDate:'',createDate:'',authorUserid:'',authorName:'',canDel:'',canEdit:'',canRead:'',bizKey:'',encryptType:'',canComment:'',status:'',isStorageDir:'',branchId:'',titleImgUrl:'',type:'',duration:'',tagIds:'',archiveType:'',imageUrls:'',linkArchives:'',readNums:'',commentNums:'',linkAds:'',linkUsers:'',extInfos:'',praiseSum:'',isHot:'',isMain:'',opDate:'',seqNo:'',pbizKey:'',ctime:'',ip:'',cityId:'',cityName:'',upNums:'',collectNums:'',relyTypes:'',relyIds:'',relySubTypes:'',relySubIds:''
            },
            //增删改查(含批量)接口
            apis:{
                list:ArchiveApi.listArchive,
                listAds:listAdvert,
                queryById: ArchiveApi.queryArchiveById,
                add: ArchiveApi.addArchive,
                edit: ArchiveApi.editArchive,
                editSomeFields: ArchiveApi.editSomeFieldsArchive,
            },
            activeTabPaneName:"0",
            imageUrls:[],
            linkAds:[],
            linkUsers:[],
            linkArchives:[], 
        }
    },
    methods: {
         //由组件扩展添加其它的初始页面的逻辑(mounted+onOpen都会调用此函数，建议只添加公共逻辑)
         initCurrData(){
            Object.assign(this.editForm,this.editFormInit)
            Object.assign(this.editForm,this.formData)
		    this.initLink(this.editForm) 
            if(this.subOpType=='add'){
                this.editForm.branchId=this.userInfo.branchId
                this.editForm.deptid=this.userInfo.deptid
                this.editForm.archiveType=this.archiveType
                this.editForm.authorUserid=this.userInfo.userid
                this.editForm.authorName=this.userInfo.username
            }
            this.activeTabPaneName="1"
            
         },
        /**
         * 检查参数是否满足调用后台接口的条件
         * @returns true / false
         */
        preParamCheck(params){
            this.calcLink(params)
            if( this.editForm.archiveContext.length>1024*1024){
                this.$message({ message: "内容太长，请调整图片大小或者减少文字，总长度不能超过1M,单张图片建议不超过50K", type: 'error' }); 
                return false;
            }
            return true;
        },

        /**
          * 设置某个关键词、按钮、输入框禁用 disabledRules['addBtn']=false
          * 判断某个对象是否可编辑 this.disabledJudge('addBtn')==false
          */
        disabledRulesInit(disabledRules){

        },
        /**
         * 对修改的字段进行判断，返回false ,将取消更新数据库,由组件扩展
         * @param {*} row 当前选中的行
         * @param {*} fieldName 修改的字段名
         * @param {*} $event 修改后的值
         * @param {*} params 将要提交服务器的参数
         * @returns true/false 返回false ,将取消更新数据库
         */
        editSomeFieldsCheck(row,fieldName,$event,params){
            params[fieldName]=$event
            return true;
        },
        //新增、编辑提交@submit="afterFormSubmit"
        saveSubmit: function (status) {
            var form=this.$refs['editFormRef'];
            if(!form){ 
                form=this.$refs['editForm'];
            } 
            form.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => { 
                        this.load.edit=true
                        let params = Object.assign({}, this.editForm);
                        if(!this.preParamCheck(params)){
                            this.load.edit=false
                            return;
                        } 
                        params.status=status
                        var func=this.apis.add
                        if(this.currOpType=='edit'){
                            func=this.apis.edit
                        }else{
                            params={params,categoryId:this.categoryId}
                        }
                        func(params).then((res) => { 
                            this.load.edit=false
                            var tips=res.data.tips;
                            if(tips.isOk){  
                                this.afterSubmit(res,tips.isOk,this.currOpType);
                            }
                            this.$notify({ position:'bottom-left',showClose:true, message: tips.msg, type: tips.isOk?'success':'error' });
                        }).catch( err =>this.load.edit=false);
                    });
                }else{
                    this.$notify({ showClose:true, message: "表单验证不通过，请修改表单数据再提交", type: 'error' });
                }
            });
        },  
		initLink(data){
			 if(data.imageUrls){
				this.imageUrls=JSON.parse(data.imageUrls)
			}else{
				this.imageUrls=[]
			}
			   if(data.linkArchives){
				this.linkArchives=JSON.parse(data.linkArchives)
			}else{
				this.linkArchives=[]
			} 
			if(data.linkAds){
				this.linkAds=JSON.parse(data.linkAds)
			}else{
				this.linkAds=[]
			} 
			if(data.linkUsers){
				this.linkUsers=JSON.parse(data.linkUsers)
			}else{
				this.linkUsers=[]
			} 
		},
		
		calcLink(data){
			if(this.imageUrls){
				data.imageUrls=JSON.stringify(this.imageUrls.map(i=>{
					return {id:i.id,imgUrl:i.imgUrl,linkUrl:i.linkUrl,imgDesc:i.imgDesc}
				}))
			}else{
				data.imageUrls=""
			}
			if(this.linkArchives){
				data.linkArchives=JSON.stringify(this.linkArchives.map(i=>{
					return {id:i.id,imgUrl:i.imgUrl,linkUrl:i.linkUrl,imgDesc:i.imgDesc}
				}))
			}else{
				data.linkArchives=""
			}
			if(this.linkAds){
				data.linkAds=JSON.stringify(this.linkAds.map(i=>{
					return {id:i.id,imgUrl:i.imgUrl,linkUrl:i.linkUrl,imgDesc:i.imgDesc}
				}))
			}else{
				data.linkAds=""
			}
			if(this.linkUsers){
				data.linkUsers=JSON.stringify(this.linkUsers.map(i=>{
					return {imgUrl:i.imgUrl,linkUrl:i.linkUrl,imgDesc:i.imgDesc}
				}))
			}else{
				data.linkUsers=""
			} 
			   
		},
		saveLink(linkType){
			this.calcLink(this.editForm)
			this.editSomeFields(this.editForm,linkType,this.editForm[linkType])
		},
        onImageSelect(imgs){
            
            if(imgs==null || imgs.length==0){
                this.imageUrls=[]
                this.calcLink(this.editForm)
                return;
            } 
            this.imageUrls= imgs.map(i=>{
                return {
                    id:i.id,
                    imgUrl:i.url,
                    imgDesc:i.name,
                    linkUrl:i.url
                }
            })
            this.calcLink(this.editForm)
        }, 
        onAdSelect(ads){
            if(ads==null || ads.length==0){
                this.linkAds=[]
                this.calcLink(this.editForm)
                return;
            } 
            this.linkAds= ads.map(i=>{
                return {
                    id:i.id,
                    imgUrl:i.imgUrl,
                    imgDesc:i.name,
                    linkUrl:i.link
                }
            })
            this.calcLink(this.editForm)
        }, 
        onArchiveSelect(archives){
            if(archives==null || archives.length==0){
                this.linkArchives=[]
                this.calcLink(this.editForm)
                return;
            }
             var curlDomain=window.location.protocol+"//"+window.location.host; //   返回https://mp.csdn.net 
                this.linkArchives= archives.map(i=>{
                    return {
                        id:i.id,
                        imgUrl:i.titleImgUrl,
                        imgDesc:i.archiveTitle,
                        linkUrl:curlDomain+'/api/m1/arc/arc/archive/showArchive?id='+i.id
                    }
                })
            this.calcLink(this.editForm)
        }, 
    },
    mounted() {

    }
}

</script>

<style scoped>

</style>